/*    This file is part of libepistle.
 *
 *    libepistle is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    libepistle is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with libepistle.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <errno.h>
#include <sys/socket.h>

#include "transfer.h"

int
recv_byte(void *buf, int fd, int *recvd, int wait, Err *err)
{
	ssize_t recv_cnt;

	*recvd = 0;

	do {
		recv_cnt = recv(fd, buf, 1,
				wait ? MSG_WAITALL : MSG_DONTWAIT);

		if (recv_cnt < 0) {
			if (errno != EINTR || errno != EAGAIN ||
			    errno != EWOULDBLOCK)
				return 0;

			err_std(err);
			return -1;
		}

		if (recv_cnt) {
			*recvd = 1;
			wait = 0;
		}
	} while (wait);

	return 0;
}

int
send_byte(uint8_t byte, int fd, int *sent, int wait, Err *err)
{
	ssize_t send_cnt;

	*sent = 0;

	do {
		send_cnt = send(fd, &byte, 1, MSG_NOSIGNAL |
				(wait ? MSG_WAITALL : MSG_DONTWAIT));

		if (send_cnt < 0) {
			if (errno != EINTR || errno != EAGAIN ||
			    errno != EWOULDBLOCK)
				return 0;

			err_std(err);
			return -1;
		}

		if (send_cnt) {
			*sent = 1;
			wait = 0;
		}
	} while (wait);

	return 0;
}

int
recv_buf(void *buf, int fd, uint32_t len, uint32_t *recvd, int wait, Err *err)
{
	ssize_t recv_cnt;

	do {
		recv_cnt = recv(fd, ((uint8_t * ) buf) + *recvd,
				len - *recvd,
				wait ? MSG_WAITALL : MSG_DONTWAIT);

		if (recv_cnt < 0) {
			if (errno != EINTR || errno != EAGAIN ||
			    errno != EWOULDBLOCK)
				return 0;

			err_std(err);
			return -1;
		}

		if ((*recvd += recv_cnt) == len)
			wait = 0;
	} while (wait);

	return 0;
}

int
send_buf(void *buf, int fd, uint32_t len, uint32_t *sent, int wait, Err *err)
{
	ssize_t send_cnt;

	do {
		send_cnt = send(fd, ((uint8_t * ) buf) + *sent,
				len - *sent, MSG_NOSIGNAL |
				(wait ? MSG_WAITALL : MSG_DONTWAIT));

		if (send_cnt < 0) {
			if (errno != EINTR || errno != EAGAIN ||
			    errno != EWOULDBLOCK)
				return 0;

			err_std(err);
			return -1;
		}

		if ((*sent += send_cnt) == len)
			wait = 0;
	} while (wait);

	return 0;
}
